"""EEG数据控制器

处理脑波数据相关的API接口
专注于原始脑波数据的接收、存储和查询
分析结果数据请使用 /analysis 接口
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, Dict, Any
from datetime import datetime
from loguru import logger

from app.config import settings
from app.services.eeg_service import EEGService
from app.schemas.eeg_upload_schemas import EEGUploadRequest

router = APIRouter(prefix="/eeg", tags=["脑波数据"])

def get_eeg_service() -> EEGService:
    """获取EEG服务实例"""
    return EEGService()


@router.post("/raw", summary="接收原始+过滤后数据")
async def receive_raw_data(
    request: EEGUploadRequest,
    service: EEGService = Depends(get_eeg_service)
):
    """接收原始脑波数据和过滤后数据
    
    每10-15秒调用一次，直接存入数据库
    
    Args:
        request: 脑波数据上传请求
        service: EEG服务实例
        
    Returns:
        dict: 接收结果
    """
    print(request)
    try:
        result = await service.receive_raw_data(request)
        return result
        
    except ValueError as e:
        logger.warning(f"原始数据接收参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"原始数据接收失败: {str(e)}")
        raise HTTPException(status_code=500, detail="原始数据接收失败")



@router.get("/history", summary="查询原始脑波历史数据")
async def get_history_data(
    id: Optional[str] = Query(None, description="会话ID"),
    room_id: Optional[str] = Query(None, description="房间ID"),
    user_id: Optional[str] = Query(None, description="用户ID"),
    create_time_start: Optional[str] = Query(None, description="创建时间开始"),
    create_time_end: Optional[str] = Query(None, description="创建时间结束"),
    update_time_start: Optional[str] = Query(None, description="更新时间开始"),
    update_time_end: Optional[str] = Query(None, description="更新时间结束"),
    limit: int = Query(settings.default_query_limit, description="返回记录数量限制"),
    service: EEGService = Depends(get_eeg_service)
):
    """查询原始脑波历史数据
    
    支持多种条件查询历史数据
    注意：此接口仅返回原始脑波数据，分析结果请使用 /analysis/history
    
    Args:
        id: 会话ID
        room_id: 房间ID
        user_id: 用户ID
        create_time_start: 创建时间开始
        create_time_end: 创建时间结束
        update_time_start: 更新时间开始
        update_time_end: 更新时间结束
        limit: 返回记录数量限制
        service: EEG服务实例
        
    Returns:
        dict: 原始脑波历史数据
    """
    try:
        result = await service.get_history_data(
            id=id,
            room_id=room_id,
            user_id=user_id,
            create_time_start=create_time_start,
            create_time_end=create_time_end,
            update_time_start=update_time_start,
            update_time_end=update_time_end,
            limit=limit
        )
        return result
        
    except Exception as e:
        logger.error(f"查询历史数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="查询历史数据失败")
